'''Wrapper for RESTful api https://sm.ms/api'''

import requests
import json
import os

BASE_PATH = 'https://sm.ms/api/v2/'

class SMMS:
    def __init__(self, username, password):
        self.login_success = False
        self.api_key = None
        self.username = username
        self.password = password

    def login(self):
        """
        登录SMMS username,password
        """
        data = {"username": self.username, "password": self.password}
        r = requests.post(BASE_PATH + 'token', data=data)
        if r.status_code != 200:
            print("请检查网络")
            return
        result = json.loads(r.text)
        if result["success"] == False:
            print("【code: {}】登录失败，请检查账号与密码。（{}）"
                  .format(result["code"], result["message"]))
            return
        self.login_success = result["success"]
        self.api_key = result["data"]["token"]
        self.headers = {"Content-Type": "multipart/form-data", "Authorization": self.api_key}
        return result["data"]

    def profile(self):
        """
        获取用户资料
        """
        r = requests.post(BASE_PATH + 'profile', headers = self.headers)
        if r.status_code != 200:
            print("请检查网络")
            return
        result = json.loads(r.text)
        if result["success"] == False:
            print("【code: {}】获取错误（{}）"
                  .format(result["code"], result["message"]))
            return
        return result["data"]

    def clear_history(self):
        """
        清除基于 IP 的临时上传历史记录
        """
        r = requests.get(BASE_PATH + 'clear', headers=self.headers)
        if r.status_code != 200:
            print("请检查网络")
            return
        result = json.loads(r.text)
        if result["success"] == False:
            print("【code: {}】清除失败（{}）"
                  .format(result["code"], result["message"]))
            return
        return result["data"]

    def history(self):
        """
        基于 IP 的临时上传历史
        """
        r = requests.get(BASE_PATH + 'history', headers=self.headers)
        if r.status_code != 200:
            print("请检查网络")
            return
        result = json.loads(r.text)
        if result["success"] == False:
            print("【code: {}】获取错误（{}）"
                  .format(result["code"], result["message"]))
            return
        return result["data"]

    def deletion(self):
        """
        图像删除
        """
        pass

    def upload_history(self, page=0):
        """
        上传历史
        """
        r = requests.get(BASE_PATH + 'upload_history', data = {"page": page}, headers=self.headers)
        if r.status_code != 200:
            print("请检查网络")
            return
        result = json.loads(r.text)
        if result["success"] == False:
            print("【code: {}】获取错误（{}）"
                  .format(result["code"], result["message"]))
            return
        return result["data"]

    def upload(self, file_path):
        """
        上传图片
        """
        if not (os.path.exists(file_path) and os.path.isfile(file_path)):
            print("请见检查文件！")
            
        files = {"smfile": open(file_path, 'rb')}
        params = {'format': 'json', 'ssl': True}
        r = requests.post(BASE_PATH + 'upload', files=files,
                          headers=self.headers, params=params)
        if r.status_code != 200:
            print("请检查网络")
            return
        result = json.loads(r.text)
        if result["success"] == False:
            print("【code: {}】上传失败（{}）"
                  .format(result["code"], result["message"]))
            return
        return result["data"]


if __name__ == '__main__':
    PATH = 'D:\\StudyProject\\BlogProject\\GiteeShare\\private\\'
    username = open(PATH + 'smms_username.txt').read()
    password = open(PATH + 'smms_password.txt').read()
    smms = SMMS(username, password)
    smms.login()
    file_path = "D:\\Pictures\\进击的巨人\\进击的巨人S3EP01.png"
    r = smms.upload(file_path)
    # r = smms.profile()
    # r = smms.clear_history()
    # r = smms.history()
    # r = smms.deletion()
    # r = smms.upload_history()


